package com.whisperarts.financer.app.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.eclipse.ui.plugin.AbstractUIPlugin;

import com.whisperarts.financer.app.Application;
import com.whisperarts.financer.app.utils.UIUtils;
import com.whisperarts.financer.dao.AccountsDAO;
import com.whisperarts.financer.model.transaction.Category;

public class DeleteCategoryAction extends Action implements 
ISelectionListener, IWorkbenchAction {

	private final IWorkbenchWindow window;
	public final static String ID = "com.whisperarts.financer.app.actions.deleteCategory";
	private IStructuredSelection selection;


	public DeleteCategoryAction(IWorkbenchWindow window) {
		this.window = window;
		setId(ID);
		setText("&Delete category");
		setToolTipText("Delete selected category");
		setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(Application.PLUGIN_ID, ISharedImages.IMG_ETOOL_DELETE));
		window.getSelectionService().addSelectionListener(this);
	}

	@Override
	public void selectionChanged(IWorkbenchPart part, ISelection incoming) {
		if (incoming instanceof IStructuredSelection) {
			selection = (IStructuredSelection) incoming;
			setEnabled(selection.size() == 1);
		}
	}

	@Override
	public void dispose() {
		window.getSelectionService().removeSelectionListener(this);
	}

	@Override
	public void run() {
		Category category = (Category) selection.getFirstElement();

		if (MessageDialog.openConfirm(window.getShell(), "Delete category", "Do you really want to delete selected category?")) {
			try {
				doRemoveCategory(category);
			} catch (Exception e) {				
				e.printStackTrace();
			}
			UIUtils.refreshCategoryNode();
		}	
	}

	private void doRemoveCategory(Category category) throws Exception {
		for (Category subCategory : category.getSub()) {
			doRemoveCategory(subCategory);
		}
		if (AccountsDAO.deleteCategory(category) == 0) {
//			for (AccountsCategory accCategory : AccountsDAO.getAccountsCategories()) {
//				for (Account account : accCategory.getAccounts()) {
//					for (Transaction transaction : account.getTransactions()) {
//						if (transaction.getCategory().getId() == category.getId()) {
//							transaction.setCategory(AccountsDAO.getCategories().get(0));
//						}
//					}
//				}
//			}				
			AccountsDAO.getCategories().remove(category.getId());				
			Category parentCategory = AccountsDAO.getCategories().get(category.getParentId());
			parentCategory.getSub().remove(category);

		} else { 
			throw new Exception("Error removing category");
		}
	}
}
